/**
 * LoginController.java
 * Created at 2017-07-06
 * Created by Jackie liu
 * Copyright (C) 2014, All rights reserved.
 */
package com.yunfeisoft.controller.base;

import com.applet.base.BaseController;
import com.applet.session.SessionModel;
import com.applet.session.UserSession;
import com.applet.utils.*;
import com.yunfeisoft.business.dao.inter.WarehouseDao;
import com.yunfeisoft.business.model.Warehouse;
import com.yunfeisoft.business.service.inter.CodeBuilderService;
import com.yunfeisoft.dao.inter.UserDao;
import com.yunfeisoft.enumeration.YesNoEnum;
import com.yunfeisoft.model.Menu;
import com.yunfeisoft.model.Organization;
import com.yunfeisoft.model.Role;
import com.yunfeisoft.model.User;
import com.yunfeisoft.service.inter.MenuService;
import com.yunfeisoft.service.inter.OrganizationService;
import com.yunfeisoft.service.inter.RoleService;
import com.yunfeisoft.service.inter.UserService;
import com.yunfeisoft.utils.ApiUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>ClassName: LoginController</p>
 * <p>Description: 用户登录Controller</p>
 * <p>Author: Jackie liu</p>
 * <p>Date: 2017-07-06</p>
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserSession userSession;
    @Autowired
    private MenuService menuService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 用户登录
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/loginIn", method = RequestMethod.POST)
    @ResponseBody
    public Response login(HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "account", "账号为空");
        validator.required(request, "pass", "密码为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        String account = ServletRequestUtils.getStringParameter(request, "account", null);
        String pass = ServletRequestUtils.getStringParameter(request, "pass", null);

        List<User> userList = userService.queryByAccount(account);

        if (userList.isEmpty()) {
            return ResponseUtils.warn("该账号不存在");
        }
        if (userList.size() > 1) {
            return ResponseUtils.warn("该账号重复，请联系管理员");
        }

        User user = userList.get(0);
        if (!MD5Utils.validPassword(pass, user.getPass())) {
            return ResponseUtils.warn("密码错误");
        }

        long nowTime = new Date().getTime();
        if (user.getBeginDate().getTime() > nowTime) {
            return ResponseUtils.warn("该账号暂时无法登陆");
        }

        if (user.getEndDate().getTime() < nowTime) {
            return ResponseUtils.warn("该账号已到期，请联系管理员续费");
        }

        if (user.getState() != YesNoEnum.YES_ACCPET.getValue()) {
            return ResponseUtils.warn("该账号已被禁用");
        }

        boolean isComplexPass = ValidateUtils.validatePasswordReg2(pass);
        if (!isComplexPass) {
            user.setSimplePass(true);
        }
        getAuthority(user);

        SessionModel sessionModel = new SessionModel();
        sessionModel.setUser(user);
        sessionModel.setToken(KeyUtils.getKey());
        user.setToken(sessionModel.getToken());

        userSession.storageSessionModel(sessionModel);
        request.setAttribute(Constants.SESSION_MODEL, sessionModel);

        String openId = request.getHeader("authority-id");
        if (StringUtils.isNotBlank(openId)) {
            User us = new User();
            us.setId(user.getId());
            us.setOpenId(openId);
            userService.modify(us);
        }
        return ResponseUtils.success("success", "/view/frame/index.htm");
    }

    /**
     * 获取用户的角色、菜单、组织机构信息
     *
     * @param user 登录用户实例
     */
    private void getAuthority(User user) {
        if (user.getIsSys() == YesNoEnum.YES_ACCPET.getValue()) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("state", YesNoEnum.YES_ACCPET.getValue());
            List<Menu> menuList = menuService.query(params);
            user.setMenuList(menuList);
        } else {
            List<Role> roleList = roleService.queryByUserId(user.getId());
            List<Menu> menuList = menuService.queryByUserId(user.getId());

            user.setRoleList(roleList);
            user.setMenuList(menuList);
        }

        Organization organization = organizationService.load(user.getOrgId());
        user.setOrganization(organization);
    }

    /**
     * 注册
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/registerAccount", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response register(HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "companyName", "公司名称为空");
        validator.required(request, "phone", "手机号为空");
        validator.required(request, "pass", "密码为空");
        validator.required(request, "confirmPass", "确认密码为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        String phone = ServletRequestUtils.getStringParameter(request, "phone", null);
        String pass = ServletRequestUtils.getStringParameter(request, "pass", null);
        String confirmPass = ServletRequestUtils.getStringParameter(request, "confirmPass", null);

        if (!pass.equals(confirmPass)) {
            return ResponseUtils.warn("两次密码输入不一致");
        }

        UserDao userDao = SpringContextHelper.getBean(UserDao.class);
        CodeBuilderService codeBuilderService = SpringContextHelper.getBean(CodeBuilderService.class);
        WarehouseDao warehouseDao = SpringContextHelper.getBean(WarehouseDao.class);

        String errorMsg = transactionTemplate.execute(new TransactionCallback<String>() {
            @Override
            public String doInTransaction(TransactionStatus transactionStatus) {
                boolean exist = userService.isDuplicatePoliceNo(null, phone);
                if (exist) {
                    return "该账号已经存在";
                }

                Date nowDate = new Date();
                Date endDate = DateUtils.addMoth(nowDate, 0);

                //创建用户
                User user = new User();
                user.setId(KeyUtils.getKey());
                user.setName(phone);
                user.setOrgId(Constants.ROOT);
                user.setState(YesNoEnum.YES_ACCPET.getValue());
                user.setPoliceNo(phone);
                user.setCreateTime(nowDate);
                user.setPass(MD5Utils.encrypt(pass));
                user.setIsSys(YesNoEnum.NO_CANCEL.getValue());
                user.setBeginDate(nowDate);
                user.setEndDate(endDate);

                //3 添加默认仓库
                String code = codeBuilderService.generateCode("WAREHOUSE", 2, user.getOrgId());

                Warehouse warehouse = new Warehouse();
                warehouse.setId(KeyUtils.getKey());
                warehouse.setCode(code);
                warehouse.setName("存货仓库");
                warehouse.setOrgId(user.getOrgId());
                warehouse.setIsDefault(YesNoEnum.YES_ACCPET.getValue());

                userDao.insert(user);
                warehouseDao.insert(warehouse);

                return null;
            }
        });

        if (StringUtils.isNotBlank(errorMsg)) {
            return ResponseUtils.warn(errorMsg);
        }
        return ResponseUtils.success("注册成功");
    }

    /**
     * 用户登出
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/loginOut", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response loginOut(HttpServletRequest request, HttpServletResponse response) {
        userSession.removeSession();
        return ResponseUtils.success("安全退出成功");
    }

    /**
     * 获取登录用户信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/loginUser", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response loginUser(HttpServletRequest request, HttpServletResponse response) {
        User user = ApiUtils.getLoginUser();
        return ResponseUtils.success(user);
    }
}
